package machine.send.service.impl;

import cn.hutool.http.HttpRequest;
import machine.bean.Msg;
import machine.bean.MsgType;
import machine.send.service.PrepareSendMsgService;
import machine.send.service.SendService;
import machine.utils.GroupUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 消息发送接口实现
 *
 * @author zhanghui145
 * @date 2021/12/25 14:15
 * @since 1.0.0
 */
@Service
public class SendServiceImpl implements SendService {

    @Autowired
    private PrepareSendMsgService prepareSendMsgService;

    private static final String URI_GROUP = "http://localhost:5700/send_group_msg?group_id=";
    private static final String URI_PRIVATE = "http://localhost:5700/send_msg?message_type=private&user_id=";
    private static final String MESSAGE = "&message=";

    @Override
    public void reply(Msg msg, String type, Integer id, String receivedMsg) {
        if (!prepareSendMsgService.msgCheck(type, receivedMsg)) {
            return;
        }
        String sendMsg;
        try {
            sendMsg = prepareSendMsgService.prepareMsg(id, receivedMsg);
        } catch (Exception e) {
            sendMsg = e.getMessage();
        }
        if (sendMsg == null) {
            return;
        }
        this.sendMsg(type, id, sendMsg);
    }

    public void sendPrivateMsg(Integer id, String msg) {
        send(URI_PRIVATE + id + MESSAGE + msg);
    }

    public void sendGroupMsg(Integer id, String msg) {
        send(URI_GROUP + id + MESSAGE + msg);
    }

    private void sendMsg(String type, Integer id, String msg) {
        if (MsgType.GROUP.getType().equals(type) && GroupUtils.contain(id)) {
            this.sendGroupMsg(id, msg);
        } else if (MsgType.PRIVATE.getType().equals(type)) {
            this.sendPrivateMsg(id, msg);
        }
    }

    private void send(String msg) {
        HttpRequest.get(msg).execute();
    }
}
